/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.dao.impl;

import com.techshop.dao.ReceiptNoteDao;
import com.techshop.model.ReceiptNote;
import java.util.List;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 * @author Hai-PC
 */
public class ReceiptNoteDaoImpl extends HibernateDaoSupport implements ReceiptNoteDao
{
    @Override
    public int getLastId()
    {
        List<ReceiptNote> list = getSession().createQuery("FROM ReceiptNote AS p ORDER BY p.id DESC").list();
        if (list.size() > 0)
        {
            return list.get(0).getId();
        }
        else
        {
            return 1;
        }
    }
    
    @Override
    public ReceiptNote getById(int receiptNoteId)
    {
        try
        {
            return (ReceiptNote) getSession().get(ReceiptNote.class, receiptNoteId);
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return null;
        }
    }

    @Override
    public boolean insert(ReceiptNote receiptNote)
    {
        try
        {
            getHibernateTemplate().save(receiptNote);
            return true;
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }
    
    @Override
    public boolean update(ReceiptNote receiptNote)
    {
        try
        {
            if (getById(receiptNote.getId()) == null)
            {
                return false;
            }
            else
            {
                getHibernateTemplate().update(getHibernateTemplate().merge(receiptNote));
                return true;
            }
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }

    @Override
    public boolean delete(ReceiptNote receiptNote)
    {
        try
        {
            if (getById(receiptNote.getId()) == null)
            {
                return false;
            }
            else
            {
                getHibernateTemplate().delete(getHibernateTemplate().merge(receiptNote));
                return true;
            }
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }
}